#!/usr/bin/env ruby

require 'socket'
require 'djb-netstrings'
require 'json_rpc'

class PeerCafeClient 
  include Socket::Constants
  include JSON_RPC

  #SERVER_ADDR = "studio.inf.unisi.ch"
  SERVER_ADDR = "localhost"
  SERVER_PORT = 8765

  def initialize(my_ip, my_port)
    @ip = my_ip
    @port = my_port
    @socket = Socket.new(AF_INET, SOCK_STREAM, 0)
    sockaddr = Socket.pack_sockaddr_in(SERVER_PORT,
                                       SERVER_ADDR)
    @socket.connect(sockaddr)

    my_data = {
      "ip" => @ip,
      "port" => @port
    }

    msg = json_request('get_peer_list', my_data) do |result, error|
      puts "Got JSON response:\n"
      result.each {|addr| puts "ip: #{addr["ip"]} -- #{addr["port"]}" }
    end

    DjbNetstrings.ns_write(@socket, msg)
    json_handle_msg(DjbNetstrings.ns_read(@socket))
  end
end
  
client = PeerCafeClient.new("23.654.34.12", rand(65000))
